/**
 * 文件格式化读写: fprintf, fscanf
 * https://www.bilibili.com/video/BV1vs411n7TH/?p=119
 */
#include "../Utils/FileIOUtils.h"

static const char *FILE_WRITE_PATH = "../Read_Write_Test/4.四则运算生成2.txt";
static const char *FILE_WRITE_RESULT_PATH = "../Read_Write_Test/4.四则运算结果2.txt";

void fprintf_test();
void fscanf_test();

int main() {
    //1.将格式化字符串, 输出到文件
    fprintf_test();
    //2.从文件中, 按照格式读取, 并给参数地址赋值
    fscanf_test();
    return EXIT_SUCCESS;
}

//1.将格式化字符串, 输出到文件
void fprintf_test() {
    FILE *file = file_open_w(FILE_WRITE_PATH);
    int len0 = file_printf(file, "%d%c%d=\n", 2, '+', 5);
    int len1 = file_printf(file, "%d%c%d=\n", 3, '*', 6);
    printf("1.将格式化字符串, 输出到文件: %s\n", FILE_WRITE_PATH);
    file_close(file);
}


//2.从文件中, 按照格式读取, 并给参数地址赋值
void fscanf_test() {
    FILE *fileRead = file_open_r(FILE_WRITE_PATH);
    FILE *fileWrite = file_open_w(FILE_WRITE_RESULT_PATH);
    int a, b, sum;
    char c;
    while (!file_eof(fileRead)) {
        //成功转换的值的个数
        int successSize = file_scanf(fileRead, "%d%c%d=\n", &a, &c, &b);
        switch (c) {
            case '+':
                sum = a + b;
                break;
            case '-':
                sum = a - b;
                break;
            case '*':
                sum = a * b;
                break;
            case '/':
                sum = a / b;
                break;
        }
        file_printf(fileWrite, "%d%c%d=%d\n", a, c, b, sum);
    }
    printf("2.从文件中, 按照格式读取, 并给参数地址赋值: %s\n", FILE_WRITE_RESULT_PATH);
    file_close(fileRead);
    file_close(fileWrite);
}
